class Cart {
    constructor() {
        this.getData()
        this.checkLogin()
        this.checkP()
        this.axiosRes()
    }
    /******axios的响应拦截********/
    axiosRes() {
        // 添加响应拦截器
        axios.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            // console.log(response);
            if (response.data.code == 401) {
                location.assign('./login.html?returnUrl=./cart.html')
            }
            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }
    //判断是否登录了
    checkLogin() {
        //获取token
        let token = localStorage.getItem('token')
        if (!token) location.assign('./login.html?returnUrl=./cart.html');
    }
    //获取购物车信息
    async getData() {
        this.checkLogin();
        //获取用户id
        let userid = localStorage.getItem('user_Id')
        //设置请求头
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        //token认证编码设置
        let token = localStorage.getItem('token')
        axios.defaults.headers.common['Authorization'] = token;
        let res = await axios.get('http://localhost:8888/cart/list?id=' + userid)
        let { status, data } = res;
        //console.log(res);
        //判断是否请求成功
        if (status !== 200) return;
        if (data.code == 401) location.assign('./login.html?returnUrl=./cart.html');
        //渲染页面
        if (data.code == 1) {
            let html = '';
            data.cart.forEach(ele => {
                // console.log(ele);
                html += `<ul class="goods-list yui3-g" data-id=${ele.goods_id}>
            <li class="yui3-u-3-8 pr">
                <input type="checkbox" class="good-checkbox">
                <div class="good-item">
                    <div class="item-img">
                        <img src="${ele.img_small_logo}">
                    </div>
                    <div class="item-msg">${ele.title}</div>
                </div>
            </li>
            <li class="yui3-u-1-8">
                <br>
            </li>
            <li class="yui3-u-1-8">
                <span class="price">${ele.current_price}</span>
            </li>
            <li class="yui3-u-1-8">
                <div class="clearfix">
                    <a href="javascript:;" class="increment mins">-</a>
                    <input autocomplete="off" type="text" value="${ele.cart_number}" minnum="1" class="itxt">
                    <a href="javascript:;" class="increment plus">+</a>
                </div>
                <div class="youhuo">有货</div>
            </li>
            <li class="yui3-u-1-8">
                <span class="sum">${ele.current_price * ele.cart_number}</span>
            </li>
            <li class="yui3-u-1-8">
                <div class="del1">
                    <a href="javascript:;" class="del-goods">删除</a>
                </div>
                <div>移到我的关注</div>
            </li>
        </ul> `
            })
            //添加到页面中去
            this.$('.cart-list').innerHTML = html
        }
    }
    // 绑定事件函数
    checkP() {
        //绑定全选按钮
        this.$('.cart-th input').addEventListener('click', this.checkQ.bind(this))
        //通过事件委托给每个单选按钮绑定点击事件
        this.$('.cart-list').addEventListener('click', this.checkQu.bind(this))
        //给数量绑定输入事件
        this.$('.cart-list').addEventListener('input', this.changeNum.bind(this))

    }
    //区别当前操作
    checkQu(ele) {
        let tar = ele.target
        if (tar.classList.contains('good-checkbox')) {
            //如果选中的是单选则调用 单选的回调函数
            this.checkMag(tar)
            //统计数量和小鸡
            this.totalSP()
            //console.log(tar);
        }
        //判断是不是点击了删除按钮
        if (tar.classList.contains('del-goods')) {
            //调用删除按钮回调函数
            this.delH(tar)
        }
        //判断是否点击了+或-
        if (tar.classList.contains('plus') || tar.classList.contains('mins')) {
            this.changeNum(ele)
        }
    }

    //修改数量的方法
    changeNum(ele) {
        //判断当前是否为输入框

        if (ele.target.type == 'checkbox') return;
        //console.log(ele.target.type)
        let input = '';
        let val = 0;
        //先判断是否为点击事件
        if (ele.type == 'click') {
            let mask = ele.target.innerHTML;
            //判断事件源是+还是-
            if (mask == '+') {
                input = ele.target.previousElementSibling
                val = input.value - 0 + 1
                console.log(ele.target.previousElementSibling);
                console.log(val, input.value);
            }
            if (mask == '-') {
                input = ele.target.nextElementSibling
                val = input.value - 1
                console.log(input);
                if (val < 1) val = 1
            }
            input.value = val
            console.log(val);
        }
        if (ele.type == 'input') {
            this.totalSP()
        }
        this.sumSprice(val, ele.target)
    }
    //小计的实现
    sumSprice(num, target) {
        //找到最大父级
        let ul = this.deep(target)
        // console.log(ul);
        // 调用获取父级下的某一个子节点  获取单价
        let price = this.getChildren(ul, '.price', 'innerHTML')
        //console.log(price, num);
        //小计
        let sum = ul.querySelector('.sum')
        sum.innerHTML = (num * price).toFixed(2)
        //修改数量  发送ajax请求  改变总价
        let goodId = ul.dataset.id
        this.sendAjaxNum(goodId, num)
        //计算总价
        this.totalSP()

    }
    time = '';
    //发送Ajax请求改变后台数据
    sendAjaxNum(goodId, sum) {
        //防抖
        clearTimeout(this.time);
        this.times = setTimeout(() => {
            axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
            axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
            let userId = localStorage.getItem('user_id');
            // 对参数编码
            let param = `goodsId=${goodId}&number=${sum}&id=${userId}`;
            axios.post('http://localhost:8888/cart/number', param).then(res => {
                // console.log(res);
            })
        }, 300)


    }








    //删除按钮事件
    delH(tar) {
        let res = this.deep(tar)
        //console.log(res);
        layer.msg('确定残忍的抛弃奴家吗?', {
            time: 20000, //20s后自动关闭
            btn: ['确定', '取消'],
            yes(index) {
                layer.close(index);
                //console.log(1111);
                //获取用户ID和商品ID和凭证
                let userId = localStorage.getItem('user_Id');
                let token = localStorage.getItem('token');
                let goodsId = res.dataset.id
                //  console.log(goodsId);
                //设置凭证编译
                axios.defaults.headers.common['Authorization'] = token;
                axios.get('http://localhost:8888/cart/remove?id=' + userId + '&goodsId=' + goodsId).then(
                    ({ status, data }) => {

                        if (status == 200 && data.code == 1) {
                            res.remove()
                        }
                    }
                )
            }
        })
    }
    //递归函数寻找父级节点
    deep(ele, tar = 'ul') {
        if (ele.nodeName == tar.toUpperCase()) {
            return ele;
        }
        return this.deep(ele.parentNode)
    }
    //全选按钮的回调函数
    checkQ(ele) {
        //console.log(ele.target);
        //获取事件源的选项属性
        let res = ele.target.checked
        //console.log(res);
        //将全选框的状态当作参数给单个选择作为状态
        this.checkO(res);
        //统计数量和小鸡
        this.totalSP();
    }
    //单个按钮的回调函数
    checkO(res) {
        //console.log(ele.target);
        //获取所有的单个选择框
        let li = document.querySelectorAll('.good-checkbox')
        //  console.log(li);
        //遍历数组设置每一个单选框的状态
        li.forEach(ele => {
            //console.log(ele);
            ele.checked = res;
        })
    }

    //单选框控制多选框的状态  只有点击单选才会触发
    checkMag(tar) {
        // console.log(111);
        if (tar.checked) {
            //获取所有的单选按钮
            let res = document.querySelectorAll('.good-checkbox')
            //遍历这个伪数组
            let rese = [...res].some(ele => {
                return !ele.checked
            });
            console.log(rese);
            if (!rese) this.$('.cart-th input').checked = true;
        } else {
            this.$('.cart-th input').checked = false;
        }
    }
    //统计数量和小鸡
    totalSP() {
        let tNum = 0;
        let tPrice = 0;
        let goodlist = document.querySelectorAll('.goods-list')
        goodlist.forEach(ul => {
            let checkbox = this.getChildren(ul, '.good-checkbox', 'checked');
            if (checkbox) {
                let num = this.getChildren(ul, '.itxt', 'value') - 0;
                let sum = this.getChildren(ul, '.sum', 'innerHTML') - 0;
                // console.log(checkbox, num, sum);
                tNum += num;
                tPrice += sum;

            }
        })
        // 设置到页面中
        this.$('.sumprice-top strong').innerHTML = tNum;
        this.$('.summoney span').innerHTML = tPrice.toFixed(2);
    }
    //获取父节点的某个子节点
    getChildren(father, children, attr = 'value') {
        return father.querySelector(children)[attr]
    }


    //节点获取
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res
    }

}
new Cart()